<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-form-item label="原先价格" prop="oldValue">
                    <el-input v-model="formData.oldValue" placeholder="价格" disabled />
                </el-form-item>
                <el-form-item label="修改价格" prop="newValue">
                    <el-input v-model="formData.newValue" placeholder="价格" allowClear />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import { editPrice } from '@/servers/goods/api/supplyChainshangpinguanli'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const type = ref()
let id: any = undefined
const popupTitle = ref()
const formData = reactive({
    oldValue: undefined,
    newValue: 0
})

const lowlimit = ref(0)

const lowLimitChange = (rule, value, callback) => {
    if (value < lowlimit.value) {
        callback(new Error('不能低于供货商结算价格'))
    } else {
        callback()
    }
}

const formRules = reactive({
    newValue: [
        {
            required: true,
            message: '请输入新价格',
            trigger: ['blur']
        },
        { validator: lowLimitChange, trigger: 'blur' }
    ]
})

const handleSubmit = async () => {
    await formRef.value?.validate()
    await editPrice(
        {
            id
        },
        {
            type: type.value,
            price: formData.newValue
        }
    )

    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (ptype: any, record: any) => {
    type.value = ptype
    id = record.id
    popupTitle.value = record.title
    lowlimit.value = record.lowLimit
    formData.oldValue = record.price
    formData.newValue = record.price
    popupRef.value?.open()
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open
})
</script>
